// 加载完成后执行
(function () {
  createRouter(window);
  listenToggleNav();
  copylinkModel();

  headerNavTransparentHandler();
  mineOpenListener();
})();

/**
 * 四舍五入（"数字" 或 "数字字符串"）
 * @param {number} precision 小数精度
 * @param {boolean} sup 自动补0，默认true
 */
function toRound(precision, sup = true) {
  // 四舍五入方法
  const round = (number, precision) => {
    precision = precision == null ? 0 : precision >= 0 ? Math.min(precision, 292) : Math.max(precision, -292);
    if (precision) {
      let pair = `${number}e`.split('e');
      const value = Math.round(`${pair[0]}e${+pair[1] + precision}`);
      pair = `${value}e`.split('e');
      return +`${pair[0]}e${+pair[1] - precision}`;
    }
    return Math.round(number);
  };
  // 取出 "数字" 和 "."
  let val = this + '';
  // NaN抛出异常，并返回 val
  if (isNaN(val)) {
    console.error('toRound can only be executed number or srting of number');
    return val;
  }
  // 正负数处理
  let value = val > 0 ? round(val, precision) : -round(-val, precision);
  // 是否补0
  return sup ? value.toFixed(precision) : value;
}

// 挂载Number、String原型链中
Number.prototype.toRound = toRound;
String.prototype.toRound = toRound;

// 是否是移动端判断
function isMobile() {
  return window.innerWidth < 768; // 假设移动端设备的宽度一般小于768px
}

// 页面置顶
function ScrollTop(top = 0) {
  $('html, body').animate({ scrollTop: top });
}

/**
 * 删除确认弹框
 * @param {string} msg 提示信息
 * @param {function} cb 回调方法
 */
function delAlter(msg, cb) {
  // 内容
  const el = modelBox(cb);
  const msgEl = document.createElement('div');
  msgEl.style = `
            font-size: 16px;
            color: #333333;
            text-align: center;
            margin: 20px;
            padding: 0;
        `;
  msgEl.textContent = msg;
  el.appendChild(msgEl);
}

/**
 * 弹框
 * @param {function} cb 回调方法, 0:取消，1:确定，-1:关闭（tipMsgSelect.checked提示信息勾选状态）
 * @returns el,contentEL,titleEl,msgEl,btnGroup,btnCancel,btnConfirm,btnClose,tipMsg,tipMsgSelect,confirmLoading,open,coles,
 */
function modelBox(cb, options = {}) {
  const cbIsFun = typeof cb == 'function';
  const config = {
    title: '提示',
    cancelLabel: '取消',
    confirmLabel: '确定',
    tipMsg: '',
    autoOpen: true,
    autoColes: true,
    ...options,
  };

  // 背景遮罩
  const el = document.createElement('div');
  el.style = `
        width: 100vw;
        height: 100vh;
        position: fixed;
        z-index: 666666;
        background: rgba(0,0,0,0.5);
        top: 0;
        left: 0;
        display: flex;
        justify-content: center;
        align-items: center;    
    `;

  // 内容框
  const contentEL = document.createElement('div');
  contentEL.style = `
        position: relative;
        background: white;
        border-radius: 10px;
        padding: 15px;
        min-width: 260px;
        max-width: 90%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    `;
  el.appendChild(contentEL);

  // 标题
  let titleEl = document.createElement('h3');
  if (config.title) {
    titleEl.textContent = config.title;
    titleEl.style = `
          font-size: 18px;
          color: #333333;
          line-height: 36px;
          font-weight: bold;
          text-align: center;
          margin: 0;
          padding: 0;
      `;
    contentEL.appendChild(titleEl);
  }

  // 内容
  const msgEl = document.createElement('div');
  msgEl.style = `
            font-size: 16px;
            color: #333333;
            text-align: center;
            margin: 20px;
            padding: 0;
        `;
  contentEL.appendChild(msgEl);

  // 按钮组
  const btnGroup = document.createElement('div');
  btnGroup.style = `display: flex;`;
  const btnStyle = `
        display: flex;
        justify-content: center;
        align-items: center;
        width: 69px;
        height: 36px;
        padding: 0;
        text-align: center;
        background: #FFFFFF;
        border: 1px solid #EDEDED;
        border-radius: 4px;
        line-height: 36px;
        font-size: 14px;
    `;

  // 取消按钮
  let btnCancel = document.createElement('button');
  if (config.cancelLabel) {
    btnCancel.style = btnStyle;
    btnCancel.style.color = '#999999';
    btnCancel.style.marginRight = '20px';
    btnCancel.textContent = config.cancelLabel;
    btnGroup.appendChild(btnCancel);
    btnCancel.addEventListener('click', function (e) {
      if (cbIsFun) cb(0);
      if (config.autoColes) coles();
    });
  }

  // 确认按钮
  let btnConfirm = document.createElement('button');
  let confirmLoading = document.createElement('i');
  if (config.confirmLabel) {
    btnConfirm.style = btnStyle;
    btnConfirm.style.background = '#FF571D';
    btnConfirm.style.color = '#ffffff';
    btnConfirm.textContent = config.confirmLabel;
    btnGroup.appendChild(btnConfirm);
    btnConfirm.addEventListener('click', function (e) {
      // 加载动画
      confirmLoading.style.marginLeft = '10px';
      confirmLoading.style.marginBottom = '-3px';
      confirmLoading.style.borderColor = 'transparent #fff #fff #fff';
      confirmLoading.classList.add('loading-icon');
      btnConfirm.appendChild(confirmLoading);
      btnConfirm.disabled = true;

      if (cbIsFun) cb(1);
      if (config.autoColes) coles();
    });
  }

  // 挂载btnGroup
  if (config.cancelLabel || config.confirmLabel) {
    contentEL.appendChild(btnGroup);
  }

  // 下次不再提示
  let tipMsg = document.createElement('label');
  let tipMsgSelect = document.createElement('input');
  if (config.tipMsg) {
    tipMsg.setAttribute('for', 'tipMsgInfo');
    tipMsg.style = `
          position: absolute;
          bottom: -40px;
          z-index: 1;
          color: white;
          display: flex;
          align-items: center;
        `;

    tipMsgSelect.setAttribute('type', 'checkbox');
    tipMsgSelect.setAttribute('id', 'tipMsgInfo');
    tipMsgSelect.style = `
          width: 18px;
          height: 18px;
          padding: 0;
          margin: 0;
          margin-right: 5px;
          display: inline-block;
        `;

    const tipMsgInfo = document.createElement('span');
    tipMsgInfo.textContent = config.tipMsg;
    tipMsg.appendChild(tipMsgSelect);
    tipMsg.appendChild(tipMsgInfo);
    contentEL.appendChild(tipMsg);
  }

  // 关闭按钮
  const btnClose = document.createElement('img');
  btnClose.src = Variable.imagesUrl + '/close.png';
  btnClose.style.position = 'absolute';
  btnClose.style.bottom = config.tipMsg ? '-80px' : '-50px';
  btnClose.addEventListener('click', function (e) {
    if (cbIsFun) cb(-1);
    if (config.autoColes) coles();
  });
  contentEL.appendChild(btnClose);

  // 打开
  const open = () => {
    if (document.documentElement.contains(el) == false) document.body.appendChild(el);
  };
  if (config.autoOpen) open();

  // 关闭
  const coles = () => {
    if (document.documentElement.contains(el) == true) document.body.removeChild(el);
  };

  return {
    el,
    contentEL,
    titleEl,
    msgEl,
    btnGroup,
    btnCancel,
    btnConfirm,
    btnClose,
    tipMsg,
    tipMsgSelect,
    confirmLoading,
    open,
    coles,
  };
}

/**
 * 消息提示
 * { type: 'success' | 'warning' | 'error' | 'info', message: String, time: Number}
 */
function tipMessage(options) {
  if (options.message == '') return;

  const info = { type: 'warning', message: '提示', time: 1000, ...options };
  const color = {
    success: '--color-success',
    warning: '--color-warning',
    error: '--color-danger',
    info: '--color-info',
  };

  const el = document.createElement('div');
  el.style = `
  display:none;
  width: 200px;
  position: fixed;
  z-index: 666666;
  top: 50px;
  left: 50%;
  border-radius: 10px;
  margin-left: -100px;
  padding: 10px 20px;
  color: white;
  background-color: var(${color[info.type]});
`;

  el.textContent = info.message;
  $(el).fadeIn('slow');

  // 挂载el
  document.body.appendChild(el);

  // 移除
  setTimeout(() => {
    $(el).fadeIn('slow', () => {
      document.body.removeChild(el);
    });
  }, info.time);

  return el;
}

// 上传文件
function fileUpload(e, elInput, elImg, cb) {
  return new Promise((resolve, reject) => {
    const cbIsFun = typeof cb == 'function';
    const target = e.target;
    const file = target.files[0];

    // 格式检查
    if (['image/png', 'image/jpg', 'image/jpeg'].indexOf(file.type) == -1) return tipMessage({ message: '仅支持 png、jpg、jpeg 格式' });

    const formData = new FormData();
    formData.append('file', file);
    uploadApi(formData)
      .then((url) => {
        if (cbIsFun) {
          cb(url);
        } else {
          $(elInput).val(url);
          // 显示结果
          if ($(elImg).attr('src')) $(elImg).attr('src', url);
          else $(elImg).text(url);
        }
        resolve(url);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

// 图片裁剪
function cropperImg(src) {
  return new Promise((resolve, reject) => {
    const image = document.createElement('img');
    image.style.height = '150px';
    image.src = src;
    const cropper = new Cropper(image, {
      aspectRatio: 1 / 1,
      viewMode: 1,
    });
    const { msgEl } = modelBox(
      (res) => {
        if (res == 1) {
          // blob二进制
          cropper.getCroppedCanvas().toBlob((blob) => {
            const formData = new FormData();
            formData.append('file', blob, 'photo.png');
            resolve(formData);
          });
        } else {
          reject();
        }
      },
      {
        title: '裁剪',
        cancelLabel: '',
      },
    );

    msgEl.appendChild(image);
  });
}

// 上传
function uploadApi(formData) {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: 'http://47.96.94.47:8228/api/common/upload',
      type: 'POST',
      data: formData,
      headers: {
        Token:
          'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzM4NCJ9.eyJpc3MiOiJ0aXl1QGJhaWtlIiwiYXVkIjoiIiwiaWF0IjoxNzA4OTA5ODcyLCJuYmYiOjE3MDg5MDk4NzUsImV4cCI6MTcwODk5NjI3MiwiZGF0YSI6eyJpZCI6MSwicm9sZV9pZHMiOlsxXSwiaGVhZF9pbWciOiJodHRwOi8vcGFuZGFpdDo4MTAwL3VwbG9hZC8yMDIzMTIxMy8xN2NiZmVlNGYzZDJkYjBkOTIwZGEwZmNlYzMyZDQyNy5wbmciLCJ1c2VybmFtZSI6ImFkbWluIiwicGhvbmUiOiIxODE3MjYyMzg4OSIsInJlbWFyayI6Ilx1NTQ3NVx1NTQ3NSIsImxvZ2luX251bSI6ODM3LCJzb3J0IjowLCJzdGF0dXMiOjEsImNyZWF0ZV90aW1lIjoiMjAyMy0xMC0yMyAxNDo0OToyOCIsInVwZGF0ZV90aW1lIjoiMjAyNC0wMi0yNiAwOToxMToxMiIsImRlbGV0ZV90aW1lIjpudWxsLCJleHBpcmVfdGltZSI6MTcwODkxNzA3Mn19.rt-1m5_DjxeWjoPaPy60LfgPTY2g74yGWix_q5E8t43k97TJTTwzsAapKTQyt28p',
      },
      cache: false,
      processData: false,
      contentType: false,
      success: function (res) {
        if (res.result) {
          const url = res.result.url;
          console.log('上传文件', url);
          tipMessage({ message: '上传成功', type: 'success' });
          resolve(url);
        } else {
          tipMessage({ message: '上传失败', type: 'error' });
          reject(res);
        }
      },
      error: function (err) {
        tipMessage({ message: '上传失败', type: 'error' });
        reject(err);
      },
    });
  });
}

/**
 * 监听nav切换, 必要条件: li 元素设置 data-role 值对应内容元素 id, 列如:
 *
 *      <ul class="nav"><li data-role="example">导航</li><ul>
 *
 *      <div id="example">内容</div>
 */
function listenToggleNav() {
  // 监听nav切换, data-role 处理对应面板 id
  $('.tab-nav .tab-nav-item').click(function (e) {
    // nav的active切换
    const siblings = $(this).siblings();
    siblings.removeClass('active');
    $(this).addClass('active');

    // 当前role
    const currentRole = $(this)[0].dataset.role;

    // 获取所有nav的role
    const roles = [currentRole];
    for (let index = 0; index < siblings.length; index++) {
      const nav = siblings[index];
      roles.push(nav.dataset.role);
    }

    // 面板(panel)切换
    roles.forEach((panelId) => {
      if (panelId == currentRole) $(`#${panelId}`).show();
      else $(`#${panelId}`).hide();
    });
  });
}

// 节流函数
function throttle(func, wait) {
  let lastTime = 0;
  return function () {
    let now = Date.now();
    if (now - lastTime > wait) {
      lastTime = now;
      func.apply(this, arguments);
    }
  };
}

// 复制链接
function copylinkModel(textToCopy = 'Copied content') {
  $('.copylink').click(
    throttle(function () {
      if (navigator.clipboard) {
        navigator.clipboard
          .writeText(textToCopy)
          .then(function () {
            // 显示提示弹窗
            $('.prompt-popup').fadeIn();

            // 5 秒后隐藏提示弹窗
            $('.prompt-popup').delay(2000).fadeOut();
          })
          .catch(function () {
            // alert("复制失败");
          });
      } else {
        // 创建一个新的 input 元素，并设置其值为要复制的文本
        var tempInput = document.createElement('input');
        tempInput.value = textToCopy;
        document.body.appendChild(tempInput);

        // 选择新的 input 元素的文本
        tempInput.select();

        // 尝试执行复制命令
        try {
          var successful = document.execCommand('copy');
          var msg = successful ? 'successful' : 'unsuccessful';
          console.log('Copy command was ' + msg);
        } catch (err) {
          console.log('Oops, unable to copy');
        }

        // 删除新的 input 元素
        document.body.removeChild(tempInput);

        // 显示提示弹窗
        $('.prompt-popup').fadeIn();

        // 5 秒后隐藏提示弹窗
        $('.prompt-popup').delay(2000).fadeOut();
      }
    }, 1000),
  ); // 限制为每秒最多执行一次
}

/**
 * 展开、折叠元素通用方法
 * @param {string} options 设置 { setELement:string, maxHeight:string, showBtn: string, hideBtn:string }
 */
function foldBox(options) {
  const el = $(`${options.setELement}`)[0];
  const offsetHeight = el.offsetHeight;
  const target = this.target;

  console.log('el', el.style);

  // 展开、收起
  if (target.innerText.trim() == options.hideBtn.trim()) {
    target.innerText = options.showBtn.trim();
    el.style.maxHeight = options.maxHeight;
  } else {
    target.innerText = options.hideBtn.trim();
    el.style.maxHeight = 'none';
  }
}

/**
 * 字符串参数转json
 * @param {string} str 字符串参数 (格式: id=12&name=)
 */
function paramToJson(str) {
  const data = {};
  let arr = str.split('&');
  arr.forEach((item) => {
    const [k, v] = item.split('=');
    data[k] = v;
  });
  return data;
}

/**
 * 通用防抖方法
 * @param {function} func 执行函数
 * @param {number} delay 防抖延迟
 */
function debounce(func, delay = 500) {
  let timer;
  return function () {
    if (timer) clearTimeout(timer);
    let firstRun = !timer;
    timer = setTimeout(() => (timer = null), delay);
    if (firstRun) func.apply(this, arguments);
  };
}

/**
 * 页面触底执行函数
 * @param {function} callback 执行函数
 */
function scrollToBottom(selector, callback = () => {}) {
  let timer = null;
  let scrollTopOld = 0;

  const scrollPage = function () {
    const $el = $(selector); // 你想检查的元素的ID
    const scrollTop = $(window).scrollTop(); // 当前滚动位置
    const viewportHeight = $(window).height(); // 视口高度
    const windowHeight = window.innerHeight || document.documentElement.clientHeight; // window高度
    const elTop = $el.offset().top; // 元素距离顶部的位置
    const elHeight = $el.height(); // 元素本身的高度

    if (windowHeight + scrollTop >= elTop + elHeight) {
      if (scrollTopOld != 0 && scrollTopOld < scrollTop) {
        clearTimeout(timer);
        timer = setTimeout(() => {
          console.log('scrollPage', scrollTopOld, scrollTop);
          callback(this);
        }, 500);
      }
      scrollTopOld = scrollTop;
    }
  };
  $(window).on('scroll', scrollPage);
}

// 显示文本域输入长度
function textareaLengthShow(e, showEl) {
  const value = e.target.value;
  const curr = value.length;
  const maxLength = e.target.maxLength;
  if (curr <= maxLength) $(showEl).html(curr + '/' + maxLength);
}

/**
 * 滚动列表到指定位置
 * @param {string} listEl 列表选择器
 * @param {string} itemEl 列表item选择器
 * @param {number} index 滚动到item的index
 */
function scrollToItem(listEl, itemEl, index = 0) {
  if (listEl && itemEl && index) {
    let firstTop = 0;
    let indexTop = 0;
    const els = $(`${listEl} ${itemEl}`);
    for (let i = 0; i < els.length; i++) {
      const item = els[i];
      if (i == 0) {
        firstTop = $(item).offset().top;
      }
      if (i == index) {
        indexTop = $(item).offset().top;
      }
    }
    $(listEl).scrollTop(indexTop - firstTop);
  }
}

// 透明头部通用处理方法
function headerNavTransparentHandler(headerEl = '.page-header-nav.transparent', hEl = '.scroll-change-header', scrollEl = '.page-main') {
  const header = $(headerEl);
  const headerH = $(headerEl).height();
  const h = $(hEl).height();
  if (header && h) {
    $(scrollEl).on('scroll', (e) => {
      const t = $(scrollEl).scrollTop();
      if (t >= h - headerH) {
        header.removeClass('transparent');
      } else {
        header.addClass('transparent');
      }
    });
  }
}

// 监听弹出个人中弹框
function mineOpenListener() {
  $('.mine-open').click(function () {
    $('#mineModal').show();

    $('#mineModal').click(function () {
      $('#mineModal').hide();
    });

    $('.mine-modal').click(function (event) {
      event.stopPropagation();
    });
  });
}
